package com.cbl;


import com.alee.utils.FileUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;

public class OperateFrame extends JFrame {


    JTextField rootPath, searchName, packagePath, prefix;
    JButton saveRootPathBtn, packagePathBtn, searchNameBtn, generatePackageBtn, prefixBtn,
            openCurrentPathBtn;
    JComboBox searchResult;
    JTextArea msg;

    String rootPathStr;  // 根路径
    String packagePathStr; // 补丁路径
    String prefixStr; // 前缀
    String searchNameStr;  // 文件名
    String selectResultStr; // 选中的查询结果
    String msgStr;  // 提示信息

    String rootPathUrl = "D:\\packagecode_settings\\rootPath.properties";
    String packagePathUrl = "D:\\packagecode_settings\\packagePath.properties";
    String prefixStrUrl = "D:\\packagecode_settings\\prefixStr.properties";

    String currentPackageDirectory;  // 当前补丁目录

    Font font1=new Font("微软雅黑", Font.BOLD,14);
    Font font2=new Font("微软雅黑", Font.PLAIN,13);
    Font font3=new Font("微软雅黑", Font.PLAIN,12);

    public OperateFrame(String title) throws HeadlessException {
        JFrame f = new JFrame(title);

        /* 根路径保存 */
        rootPath = new JTextField();
        rootPath.setFont(font2);
        rootPath.setBounds(50, 20, 220, 30);
        rootPathStr = FileOperate.readText(rootPathUrl, "rootPath");
        rootPath.setText(rootPathStr);
        saveRootPathBtn = new JButton("设置根路径");
        saveRootPathBtn.setBounds(300, 20, 150, 30);
        saveRootPathBtn.setFont(font1);
        saveRootPathBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            rootPathStr = rootPath.getText();
            if (!StringUtils.existBlank(new String[]{rootPathStr})) {
                FileOperate.writeText(rootPathUrl, "rootPath", rootPathStr);
                msg.setText("操作" + UUIDUtils.getRandom() + "：保存成功");
                msg.setForeground(new Color(208,132,32));
            } else {
                msg.setText("操作" + UUIDUtils.getRandom() + "：请填写必填项");
                msg.setForeground(Color.RED);
            }
            }
        });
        saveRootPathBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        /* 生成补丁位置 */
        packagePath = new JTextField();
        packagePath.setFont(font2);
        packagePath.setBounds(480, 20, 220, 30);
        packagePathStr = FileOperate.readText(packagePathUrl, "packagePath");
        packagePath.setText(packagePathStr);
        packagePathBtn = new JButton("设置补丁位置");
        packagePathBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        packagePathBtn.setFont(font1);
        packagePathBtn.setBounds(730, 20, 150, 30);
        packagePathBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                packagePathStr = packagePath.getText();
                if (!StringUtils.existBlank(new String[]{packagePathStr})) {
                    FileOperate.writeText(packagePathUrl, "packagePath", packagePathStr);
                    msg.setText("操作" + UUIDUtils.getRandom() + "：保存成功");
                    msg.setForeground(new Color(208,132,32));
                } else {
                    msg.setText("操作" + UUIDUtils.getRandom() + "：请填写必填项");
                    msg.setForeground(Color.RED);
                }
            }
        });


        /* 前缀设置 */
        prefix = new JTextField();
        prefix.setFont(font2);
        prefix.setBounds(50, 60, 220, 30);
        prefixStr = FileOperate.readText(prefixStrUrl, "prefix");
        prefix.setText(prefixStr);
        prefixBtn = new JButton("设置前缀");
        prefixBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        prefixBtn.setFont(font1);
        prefixBtn.setBounds(300, 60, 150, 30);
        prefixBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                prefixStr = prefix.getText();
                if (!StringUtils.existBlank(new String[]{prefixStr})) {
                    FileOperate.writeText(prefixStrUrl, "prefix", prefixStr);
                    msg.setText("操作" + UUIDUtils.getRandom() + "：保存成功");
                    msg.setForeground(new Color(208,132,32));
                } else {
                    msg.setText("操作" + UUIDUtils.getRandom() + "：请填写必填项");
                    msg.setForeground(Color.RED);
                }
            }
        });

        /* 查找文件名 */
        searchName = new JTextField();
        searchName.setFont(font2);
        searchName.setBounds(480, 60, 220, 30);

        searchNameBtn = new JButton("文件名搜索");
        searchNameBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        searchNameBtn.setFont(font1);
        searchNameBtn.setBounds(730, 60, 150, 30);
        searchNameBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchNameStr = searchName.getText();
                if (!StringUtils.existBlank(new String[]{searchNameStr,prefixStr,rootPathStr,packagePathStr})) {
                    File folder = new File(rootPathStr);// 默认目录
                    String keyword = searchNameStr;
                    if (searchNameStr.lastIndexOf(".java") != -1) {
                        // 如果是java文件，那么转为class文件
                        keyword = searchNameStr.substring(0, searchNameStr.lastIndexOf("java")) + "class";
                    }

                    if (!folder.exists()) {// 如果文件夹不存在
                        System.out.println("目录不存在：" + folder.getAbsolutePath());
                        return;
                    }

                    // 查找之前清空下拉框的所有内容
                    searchResult.removeAllItems();
                    searchResult.addItem("暂无查询结果");


                    File[] result = FileOperate.searchFile(folder, keyword);// 调用方法获得文件数组
                    System.out.println("在 " + folder + " 以及所有子文件时查找对象" + keyword);
                    System.out.println("查找了" + FileOperate.countFiles + " 个文件，" + FileOperate.countFolders + " 个文件夹，共找到 " + result.length + " 个符合条件的文件：");
                    for (int i = 0; i < result.length; i++) {// 循环显示文件
                        File file = result[i];
                        System.out.println(file.getAbsolutePath() + " ");// 显示文件绝对路径
                        searchResult.removeItem("暂无查询结果");
                        String filePath = file.getAbsolutePath();
                        searchResult.addItem(filePath);
                    }
                    msg.setText("操作" + UUIDUtils.getRandom() + "：在 " + folder + " 以及所有子文件时查找对象" + keyword +
                            "\n查找了" + FileOperate.countFiles + " 个文件，" + FileOperate.countFolders + " 个文件夹，共找到 " + result.length + " 个符合条件的文件");
                    msg.setForeground(new Color(208,132,32));
                } else {
                    msg.setText("操作" + UUIDUtils.getRandom() + "：请填写必填项");
                    msg.setForeground(Color.RED);
                }
            }
        });


        /* 搜索结果 */
        String[] str = {};
        searchResult = new JComboBox(str);
        searchResult.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        searchResult.setFont(font2);
        searchResult.addItem("暂无查询结果");
        searchResult.setBounds(50, 100, 830, 30);
        searchResult.setRenderer(new Render());  // 设置tooltip

        /* 一键生成补丁 */
        generatePackageBtn = new JButton("一键生成补丁");
        generatePackageBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        generatePackageBtn.setFont(font1);
        generatePackageBtn.setBounds(730, 140, 150, 30);
        generatePackageBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selectResultStr = (String) searchResult.getSelectedItem();

                if (!StringUtils.existBlank(new String[]{rootPathStr,prefixStr,packagePathStr,searchNameStr,selectResultStr})
                    && !selectResultStr.equals("暂无查询结果")) {
                    String filePath = (String) searchResult.getSelectedItem();
                    String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1); // 得到文件名
                    // 文件夹的处理：\改成点，并且截取前缀之后的路径
                    String directoryName = filePath.substring(0, filePath.lastIndexOf("\\"));  // 文件夹名：只有一层
                    directoryName = directoryName.substring(directoryName.lastIndexOf(prefixStr)).replace('\\','.');
                    filePath = packagePathStr + "\\" + directoryName + "\\" + fileName;

                    currentPackageDirectory = packagePathStr + "\\" + directoryName;  // 当前补丁位置

                    // 如果存在文件夹，那么创建，如果不存在，那么新建
                    FileOperate.createFile(filePath);
                    // 复制文件
                    FileOperate.copyFileUsingFileStreams(new File(selectResultStr), new File(filePath));
                    msg.setText("操作" + UUIDUtils.getRandom() + "：补丁生成成功");
                    msg.setForeground(new Color(208,132,32));
                } else if (selectResultStr.equals("暂无查询结果")) {
                    msg.setText("操作" + UUIDUtils.getRandom() + "：暂无查询结果");
                    msg.setForeground(Color.RED);
                }
                else {
                    msg.setText("操作" + UUIDUtils.getRandom() + "：请填写必填项");
                    msg.setForeground(Color.RED);
                }
            }
        });

        openCurrentPathBtn = new JButton("打开当前补丁目录");
        openCurrentPathBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        openCurrentPathBtn.setFont(font1);
        openCurrentPathBtn.setBounds(730, 180, 150, 30);
        openCurrentPathBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!StringUtils.existBlank(new String[] {currentPackageDirectory})) {
                    try {
                        Runtime.getRuntime().exec("explorer " + currentPackageDirectory); // 打开当前补丁目录
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    msg.setText("操作" + UUIDUtils.getRandom() + "：补丁位置" + currentPackageDirectory);
                    msg.setForeground(new Color(208,132,32));
                } else {
                    msg.setText("操作" + UUIDUtils.getRandom() + "：暂未检测到当前补丁目录，请打补丁后重试！");
                    msg.setForeground(Color.RED);
                }
            }
        });

        /* 消息 */
        msg = new JTextArea();
        msg.setFont(font3);
        msg.setBounds(50, 140, 650, 70);
        msg.setEditable(false);





        f.add(rootPath);
        f.add(saveRootPathBtn);
        f.add(prefix);
        f.add(prefixBtn);
        f.add(packagePath);
        f.add(packagePathBtn);
        f.add(searchName);
        f.add(searchNameBtn);
        f.add(searchResult);
        f.add(generatePackageBtn);
        f.add(msg);
        f.add(openCurrentPathBtn);

        // 回车搜索
        f.getRootPane().setDefaultButton(searchNameBtn);

        f.setIconImage(new ImageIcon(getClass().getResource("images/icon.png")).getImage());
        f.setSize(1000, 270);
        f.setLocationRelativeTo(null);
        f.setLayout(null);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//退出应用程序

    }

    /**
     * tooltip
     */
    class Render extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            JLabel listCellRendererComponent = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            listCellRendererComponent.setToolTipText(String.valueOf(value));
            return listCellRendererComponent;
        }
    }
}
